<template>
    <div class="edu-page-warp">
        <condition-card
            @reset="reset"
            @search="onSubmit"
            label-width="120px"
        >
            <el-col :span="8">
                <el-form-item :label="$t('label.nowGrade')">
                    <el-date-picker
                        v-model="queryForm.grade"
                        type="year"
                        value-format="yyyy"
                        :clearable="false"
                        :placeholder="$t('message.plzSelect')" style="width:100%"
                        @change="handleGradeChanged"
                    >
                    </el-date-picker>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="结业年级">
                    <el-date-picker
                        v-model="queryForm.completionYear"
                        type="year"
                        value-format="yyyy"
                        :placeholder="$t('message.plzSelect')" style="width:100%"
                        >
                    </el-date-picker>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="预科生专业">
                    <el-select v-model="queryForm.classId"  style="width:100%" clearable filterable>
                         <el-option v-for="(item,index) in options.classes" :key="'class-'+index"  :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
            </el-col>
            <!--动态生成志愿-->
            <el-col :span="8" v-for="(row,index) in queryForm.list" :key="index">
                <el-form-item :label="row.label" >
                    <el-select v-model="row.value"  style="width:100%" clearable filterable>
                         <el-option v-for="(item,index) in options.major" :key="'zy-'+index"  :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="填报状态" >
                    <el-select v-model="queryForm.applyStatus"  style="width:100%" clearable>
                        <el-option v-for="(item,index) in options.applyStatus" :key="'applyStatus-'+index"  :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="录取专业" >
                    <el-select v-model="queryForm.admissionProfession"  style="width:100%" clearable filterable>
                        <el-option v-for="(item,index) in options.major" :key="'major-'+index"  :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
            </el-col>
        </condition-card>
        <el-card shadow="never">
            <div class="edu-page-title">{{title}}</div>
            <el-row>
                <el-col :span="4">
                    <el-input
                        v-model="queryForm.keyword"
                        :placeholder="$t('score.failScoreManage.pleaseInt')"
                        @keyup.enter.native="onSubmit"
                        style="width:200px"
                    >
                        <i
                            class="el-icon-search"
                            slot="suffix"
                            style="margin-top:10px;cursor:pointer"
                            @click="onSubmit"
                        ></i>
                    </el-input>
                </el-col>
                <!-- <el-col :span="8">
                        <div class="empty-box" />
                </el-col> -->
                <el-col :span="20" v-if="type==1">
                    <div class="float-right empty-box">
                        <el-button @click="onExport">{{$t('message.export')}}</el-button>
                        <el-button  @click="handlePublish(1)">{{$t('message.publish')}}</el-button>
                        <el-button  @click="handlePublish(0)">取消发布</el-button>
                        <el-button type="primary" @click="exportNames">录取学生名单</el-button>
                        <el-button type="primary" @click="recruit">录取</el-button>
                    </div>
                </el-col>
            </el-row>
            <el-row>
                <el-col>
                    <edu-table
                        :url="getUrl()"
                        ref="mainTable"
                        :order="false"
                        :selection="type==1"
                        @selection-change="handleSelectionChange"
                    >
                        <el-table-column :label="$t('label.stuCode')"   width="100" fixed="left" prop="studentCode"/>
                        <el-table-column :label="$t('label.stuName')"  width="100" fixed="left" prop="studentName" show-overflow-tooltip />
                        <el-table-column label="预科生专业"  width="165" fixed="left" prop="className" show-overflow-tooltip />
                        <el-table-column :label="$t('label.nowGrade')" width="100" prop="grade"/>
                        <el-table-column label="结业年级" width="100" prop="completionYear"/>
                        <el-table-column :label="$t('label.college')"  width="160" prop="facultyI18n"/>
                        <el-table-column :label="item.label" v-for="(item,index) in queryForm.list" :key="index" show-overflow-tooltip width="200">
                            <template slot-scope="scope">
                               {{getMajorName(index,scope.row)}}
                            </template>
                        </el-table-column>
                        <el-table-column label="录取专业"  prop="admissionProfessionName" width="200" show-overflow-tooltip>
                             <template slot-scope="scope">
                               {{scope.row.admissionProfession?scope.row.admissionProfessionName+"("+scope.row.admissionProfession+")":null}}
                            </template>
                        </el-table-column>
                        <el-table-column label="填报状态" width="100" align="center">
                            <template slot-scope="scope">
                                <el-tag v-if="getApplyStatus(scope.row)">已填报</el-tag>
                                <el-tag v-else type="info">未填报</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column
                            v-if="type==1"
                            label="发布状态"
                            show-overflow-tooltip
                            min-width="100"
                            align="center"
                        >
                            <template slot-scope="scope">
                                <el-tag v-if="scope.row.publish == 1" type="success" size="mini">已发布</el-tag>
                                <el-tag v-else  size="mini">未发布</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="联系电话" width="150" show-overflow-tooltip prop="telephone"/>
                        <el-table-column label="联系地址" width="150" show-overflow-tooltip prop="address"/>
                        <el-table-column :label="$t('label.operation')" width="100" fixed="right" v-if="type==2">
                            <template slot-scope="scope">
                                <div v-if="scope.row.id">
                                    <el-button :disabled="scope.row.admissionProfession!=null&&scope.row.admissionProfession!=''" type="text" @click="handleRecruit(scope.row)">调剂</el-button>
                                    <!-- <el-button :disabled="scope.row.admissionProfession==null||scope.row.admissionProfession==''" type="text" @click="handleDelete(scope.row)">{{$t('message.delete')}}</el-button> -->
                                </div>
                            </template>
                        </el-table-column>
                    </edu-table>
                </el-col>
            </el-row>
        </el-card>
         <edu-dialog
            :visible.sync="dialogVisible"
            title="调剂录取"
            ref="formDialog"
            @close="closeDialog"
            @confirm="confirmDialog"
            width="600px"
        >
         <el-form :model="submitForm" ref="submitForm" label-width="100px" label-suffix="：">
                <el-row>
                      <el-form-item label="绩点成绩" >
                          <el-col :span="20">
                              {{submitForm.gradePoint}}
                          </el-col>
                      </el-form-item>
                </el-row>
                <el-row>
                    <el-table :data="studentData" style="width:100%;margin-bottom:18px" border>
                        <el-table-column label="填报志愿"   prop="order" width="110"/>
                        <el-table-column label="填报专业"   prop="choiceName"/>
                        <el-table-column label="面试成绩"   prop="interviewScore" width="100"/>
                        <el-table-column label="综合成绩"   prop="fianlScore" width="100"/>
                    </el-table>
                </el-row>
                <el-row>
                      <el-form-item label="录取专业">
                          <el-col :span="20">
                               <el-select v-model="submitForm.admissionProfession"  style="width:100%" clearable filterable>
                                    <el-option v-for="(item,index) in options.recruitMajor" :key="'major-'+index"  :label="item.label+'('+item.value+')'" :value="item.id">
                                        <span style="float: left">{{ item.label }}({{item.value}})</span>
                                        <span style="float: right; color: #8492a6; font-size: 13px">剩余名额 {{item.num}}人</span>
                                    </el-option>
                                </el-select>
                          </el-col>
                      </el-form-item>
                </el-row>
         </el-form>
         </edu-dialog>
    </div>
</template>
<script>
import * as APIs from "common/src/api/preparatoryGraduation/enroll"
import examinationStudentsApi from "common/src/api/welcomeService/examinationStudents";
import tools from 'common/src/views/underGraduationDesign/tools.js';
export default {
    name: "recruitComponent",
    props:["type"],
    data() {
        return {
            title:this.type==1?"录取管理":"调剂录取专业",
            number:null,
            queryForm:{
                grade:null,
                completionYear:null,
                list:[],
                applyStatus:null,
                admissionProfession:null,
                keyword:null,
                classId:null
            },
            options:{
                applyStatus:[],
                major:[],
                recruitMajor:[],
                classes:[]
            },
            dialogVisible:false,
            submitForm:{
                id:null,
                admissionProfession:null,
                gradePoint:null
            },
            studentData:null,
            multipleSelection:[]
        }
    },
    mounted(){
        this.queryForm.grade=((new Date()).getFullYear()-1).toString();
        //获取筛选条件数据
        this.getMajorNumber();
        this.initOption();
        this.handleGradeChanged(this.queryForm.grade);
        //获取列表数据
        this.onSubmit();
    },
    methods:{
        reset(){
            this.queryForm.grade=((new Date()).getFullYear()-1).toString();
            this.queryForm.completionYear=null;
            this.queryForm.applyStatus=null;
            this.queryForm.keyword=null;
            this.handleGradeChanged(this.queryForm.grade);
            this.onSubmit();
        },
        getParam(){
            let param=_.cloneDeep(this.queryForm)
            param.grade=param.grade;
            param.list=[];
            this.queryForm.list.forEach((row,index)=>{
                if(row.value){
                    param.list.push({
                        "level":index+1,
                        "choice":row.value
                    })
                }
            });
            return param;
        },
        onSubmit(){
            this.$refs.mainTable.search(this.getParam());
        },
        getUrl(){
            return APIs.getListPage()
        },
        convertNum(n){
            if(n<=0||n>10){
                throw "valid error"
            }
            let arr=['','一','二','三','四','五','六','七','八','九','十']
            return '志愿'+arr[n]
        },
        initOption(){
            this.options.applyStatus.push({
                label:'已填报',
                value:1
            });
            this.options.applyStatus.push({
                label:'未填报',
                value:0
            });
        },
        getMajorNumber(){
            APIs.getAuthority().then(res=>{
                if(res.code==200){
                    if(res.data){
                        this.number=res.data.choiceNumber;
                        if(this.number>10){
                            this.number=10;
                        }
                        for(let i=1;i<=this.number;i++){
                            this.queryForm.list.push({
                                label:this.convertNum(i),
                                value:null
                            })
                        }
                    }
                }
            });
        },
        recruit(){
            let completionYear = this.queryForm.completionYear || Number(this.queryForm.grade) + 1;
            this.$eduConfirm(`是否对结业年级${completionYear}的预科生，执行自动录取?`, this.$t('message.prompt'))
                .then(() =>{
                    APIs.admissionStudent({completionYear:completionYear}).then(res=>{
                        if(res.code==200){
                            this.$message({
                                type:"success",
                                message:'录取成功'
                            });
                            this.onSubmit();
                        }
                    })
            })
        },
        exportNames(){
            let loading = this.$loading({
                lock: true,
                text: "Loading",
                spinner: "el-icon-loading",
                background: "rgba(255, 255, 255, .48)"
            });
            APIs.exportList2(this.getParam()).then(res=>{
                if(res.code==200){
                    this.delayRequest(res.data.key,loading);
                }
            })
        },
        async delayRequest(key, loading) {
            await new Promise(resolve => setTimeout(resolve, 5000));
            examinationStudentsApi.getReportStatus(key)
                .then(res => {
                    if (res.code == 200 && res.data.status) {
                        let path =examinationStudentsApi.exportUrl + res.data.path;
                        window.location.href=path;
                        loading.close();
                    } else {
                        this.delayRequest(key, loading);
                    }
                })
                .catch(ex => {
                    this.delayRequest(key, loading);
                });
        },
        getMajorName(index,row){
            if(index<row.list.length){
                return row.list[index].choiceName+"("+row.list[index].choice+")";
            }
            return null;
        },
        getApplyStatus(row){
            return row.applyStatus==1?true:false
        },
        handleRecruit(row){
            this.dialogVisible=true;
            this.submitForm.id=row.id;
            this.options.recruitMajor=[];
            //1.获取个人成绩
            APIs.getOneScore({studentCode:row.studentCode}).then(res=>{
                if(res.code==200){
                    //绑定成绩信息
                    this.submitForm.gradePoint=res.data.gradePoint;
                    //面试成绩处理
                    let interviewScores=Array.apply(null, Array(row.list.length)).map(() => '')
                    if(res.data.interviewResult){
                        interviewScores=res.data.interviewResult.split(',')
                    }
                    //综合成绩处理
                    let fianlScores=Array.apply(null, Array(row.list.length)).map(() => '')
                    if(res.data.finalGrade){
                        fianlScores=res.data.finalGrade.split(',')
                    }
                    //志愿数据绑定
                    row.list.forEach((r,index)=>{
                        r.order=this.convertNum(index+1)
                        r.interviewScore=interviewScores[index]
                        r.fianlScore=fianlScores[index]
                    })
                    this.studentData=row.list;
                    //2.每次重新获取专业列表，招生人数验证
                    APIs.getListPageURL2({condition:{grade:row.completionYear},pageNum_:1,pageSize_:1000}).then(res_=>{
                        if(res.code==200){
                            //过滤录取专业
                            let majors_=res_.data.list.filter(m=>{
                                let obj=m.list.find(m_=>m_.preparatoryProfession==row.classId);
                                return obj?true:false
                            })
                            majors_=majors_.map(m=>{
                                return {
                                    label:m.professionName,
                                    value:m.profession,
                                    num:m.professionNumber-m.enrollment,
                                    id:m.id
                                }
                            })
                            this.options.recruitMajor=majors_;
                        }
                    });
                }
            })
        },
        handleDelete(row){
            this.$eduConfirm(
                this.$t('message.areYouSureDelete'),
                this.$t('message.prompt'),
                { confirmButtonText: this.$t('message.confirm'), cancelButtonText: this.$t('message.cancel'), type: "warning" }
            ).then(()=> {
                APIs.deleteStudentRecruit({id:row.id}).then(res=>{
                    if(res.code==200){
                        this.$message({
                            type:'success',
                            message:this.$t('message.deleteSuccess')
                        })
                        this.onSubmit();
                    }
                })
            });
        },
        closeDialog(){
            this.submitForm.admissionProfession=null;
            this.submitForm.id=null;
        },
        confirmDialog(){
            if(this.submitForm.admissionProfession==null){
                this.$message({
                    type:'warning',
                    message:'请选择录取专业'
                })
                return;
            }
            let option=this.options.recruitMajor.find(m=>m.id==this.submitForm.admissionProfession);
            if(option&&option.num==0){
                this.$message({
                    type:'warning',
                    message:'该专业人数已满'
                })
                return;
            }
            APIs.editStudentVolunteer({
                admissionProfession:option.value,
                id:this.submitForm.id,
                settingId:option.id
            }).then(res=>{
                if(res.code==200){
                    this.$message({
                        type:'success',
                        message:this.$t('message.submitSuccess')
                    })
                    this.dialogVisible=false;
                    this.onSubmit();
                }
            })
        },
        handleGradeChanged(val){
            //清空志愿与专业
            this.queryForm.list.forEach(row=>row.value=null);
            this.queryForm.admissionProfession=null;
            this.queryForm.classId=null;
            this.options.major=[];
            this.options.classes=[];
            APIs.getListPageURL2({condition:{grade:Number(val)+1},pageNum_:1,pageSize_:100}).then(res=>{
                if(res.code==200){
                    //去重复项
                    let codes=new Set();
                    res.data.list.forEach(p=>{
                        if(!codes.has(p.profession)){
                            codes.add(p.profession);
                            p.isValid=true;
                        }
                    });
                    this.options.major=res.data.list.filter(p=>p.isValid).map(m=>{
                        return {
                            label:m.professionName+"("+m.profession+")",
                            value:m.profession
                        }
                    })
                }
            });
            this.handleClasses();
        },
        handleSelectionChange(val){
            this.multipleSelection=val;
        },
        handlePublish(val){
            if(this.multipleSelection.length == 0){
                this.$message({
                    type:"error",
                    message: '至少选择一项'
                });
                return;
            }
            let param={
                studentId:this.multipleSelection.map(row=>row.studentCode),
                publish:val
            }
            APIs.publish(param).then(res=>{
                if(res.code==200){
                    this.$message({
                    type:"success",
                        message: this.$t('course.operateSuccess')
                    });
                    this.onSubmit();
                }
            })
      },
      handleClasses(){
        //预科生班级
        APIs.getClassList(
            {pageNum_:1,pageSize_:100,condition:{grade:this.queryForm.grade }}
        ).then(res=>{
            if(res.code==200){
                this.options.classes=res.data.list.map(major_=>{
                    return {
                        label:major_.className,
                        value:major_.id.toString()
                    }
                })
            }
        });
      },
    // 导出
    onExport() {
      let data ={};
      data.grade = this.queryForm.grade;
      APIs.exporrecruitComponent(data).then(res => {
        if (res.code == 200) {
          tools.downloadFile(res.data.key, '录取管理.xls', null, this);
        }
      })
    },
  }
}
</script>

